package communication.gamemaster;

import java.io.IOException;
import java.util.ArrayList;

import communication.ServerConnectionHandle;
import communication.Message;
import communication.MessageFactory;
import communication.MessageType;
import java.net.SocketException;
import communication.message.GameId;
import communication.message.GameMasterLogin;
import communication.message.GameOver;
import communication.message.GameState;
import communication.message.NextPlayer;
import communication.message.Player;
import exception.BadXMLException;
import exception.ParseException;

/***
 * 
 * @author Łukasz Wrzesiński
 * 
 */
public class ServerHandle extends ServerConnectionHandle {

	public ServerHandle(String ip, int port) {
		super(ip, port);
	}

	public void connect(GameMasterLogin login) throws IOException {

		super.connect();
		Message msg = new Message(MessageType.GAME_MASTER_LOGIN);
		msg.setGameMasterLogin(login);
		super.send(msg);
	}

	public void disconnect() throws IOException {
		super.disconnect();
	}

	public void beginGame(GameId id, ArrayList<Player> players) throws IOException, SocketException {
		Message msg = new Message(MessageType.BEGIN_GAME);
		msg.setGameId(id);
		for (Player player : players)
			msg.addPlayer(player);
		super.send(msg);
	}

	public void sendGameState(GameId id, NextPlayer player, GameState state)
			throws IOException {
		Message msg = new Message(MessageType.GAME_STATE);
		msg.setGameId(id);
		msg.setNextPlayer(player);
		msg.setGameState(state);
		super.send(msg);
	}

	public void sendResults(GameId id, GameOver info, GameState state)
			throws IOException {
		Message msg = new Message(MessageType.GAME_STATE);
		msg.setGameId(id);
		msg.setGameOver(info);
		msg.setGameState(state);
		super.send(msg);
	}

	public Message receiveMessage() throws ParseException, BadXMLException, SocketException {
		String s = super.receive();
		Message msg = null;
		msg = MessageFactory.fromString(s.trim());
		return msg;
	}
}